package com.pure.view
{
	import com.pure.ApplicationFacade;
	import com.pure.model.UserProxy;
	import com.pure.model.vo.UserVO;
	import com.pure.util.MvcEvent;
	import com.pure.view.components.UserForm;
	
	import flash.events.Event;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class UserFormMediator extends Mediator
	{
		public static const NAME:String = "UserFormMediator";
		
		private var userProxy:UserProxy;
		
		public function UserFormMediator(viewComponent:UserForm)
		{
			super(NAME, viewComponent);
		}
		
		/**
		 * When the object of UserFormMediator be register to facade, the method will execute.
		 */
		override public function onRegister():void
		{
			userForm.addEventListener(MvcEvent.SAVE, onSave);
			
			userProxy = UserProxy( facade.retrieveProxy( UserProxy.NAME ) );
		}
		
		/**
		 * The UserFormMediator only care about the notification in the list below.
		 */
		override public function listNotificationInterests():Array
		{
			return [
					ApplicationFacade.EDIT_USER,
					ApplicationFacade.CREATE_USER
				   ];
		}
		
		/**
		 * Do handling after others had used method --- sendNotification( name, body );
		 */
		override public function handleNotification( note:INotification ):void
		{
			switch ( note.getName() )
			{
				case ApplicationFacade.EDIT_USER:
					userForm.setUser( UserVO( note.getBody() ) );
					break;
				case ApplicationFacade.CREATE_USER:
					userForm.setUser();
					break;
			}
		}		
		private function get userForm():UserForm
		{
			return viewComponent as UserForm;	// viewComponent is declear in Mediator
		}
		
		/**
		 * ************ functions for help ******************
		 */
		// communicate with the controller
		private function onSave(event:Event):void
		{
			sendNotification(ApplicationFacade.CMD_SAVE_USER, userForm.user);
		}
	}
}